package com.isesol.arch.common.utils.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

/**
 * 类反射工具
 *
 */
public class ReflectUtils {

    private static Logger logger = LoggerFactory.getLogger(ReflectUtils.class);

    /**
     * <p>通过getter解析输出属性</p>
     * <p>结果：private String userName;</p>
     * @param clazz
     */
    public static void parsePropertyFromFromGetters(Class<?> clazz) {
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            String methodName = method.getName();
            if (methodName.startsWith("get")) {
                String propertyName = methodName.replace("get", "");
                propertyName = StringUtils.lowerCase(propertyName.substring(0, 1)) + propertyName.substring(1);
                if (propertyName.equals("class")) {
                    continue;
                }
                String returnType = method.getReturnType().getName();
                returnType = returnType.replace("java.util.", "");
                returnType = returnType.replace("java.lang.", "");
                System.out.println("private " + returnType + " " + propertyName + ";");
            }
        }
    }

    /**
     * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
     *
     * 如向上转型到Object仍无法找到, 返回null.
     */
    public static Field getAccessibleField(final Class<?> clazz, final String fieldName) {
        Assert.hasText(fieldName, "fieldName");
        Field field = null;

        String[] propertyNames = StringUtils.split(fieldName, ".");

        // 根据点号分割的属性名称循环
        for (String loopFieldName : propertyNames) {
            // 如果当前类没有指定属性转到父类查询
            for (Class<?> superClass = field == null ? clazz : field.getType(); superClass != Object.class; superClass = superClass
                    .getSuperclass()) {
                try {
                    if (superClass == null && field != null && field.getType() == List.class) {
                        Type genericType = field.getGenericType();
                        Type[] types = ((ParameterizedType) genericType).getActualTypeArguments();
                        Type type = types[0];
                        field = ((Class<?>) type).getDeclaredField(loopFieldName);
                        field.setAccessible(true);

                        // 处理属性是抽象类的情况
                        setAbstractField(clazz, field, loopFieldName);

                        // 到达最后一级，退出循环
                        break;
                    } else {
                        field = superClass.getDeclaredField(loopFieldName);
                        field.setAccessible(true);

                        // 处理属性是抽象类的情况
                        setAbstractField(clazz, field, loopFieldName);
                        break;
                    }
                } catch (NoSuchFieldException e) {//NOSONAR
                    // Field不在当前类定义,继续向上转型
                } catch (ClassNotFoundException e) {
                    logger.error("处理抽象属性时：", e);
                }
            }
        }
        return field;
    }

    /**
     * @param clazz
     * @param field
     * @param loopFieldName
     * @throws ClassNotFoundException
     */
    protected static void setAbstractField(final Class<?> clazz, Field field, String loopFieldName) throws ClassNotFoundException {
        // 判断是否为抽象类
        if (Modifier.isAbstract(field.getType().getModifiers())) {
            // 如果遇到方法返回的是抽象类，并且配置文件中进行了定义，例如：User类的getUserInfo()返回的是AbstractUserInfo
            // 通过下面的定义就可以避免从抽象类中获取不到属性的问题
            // com.runchain.arch.entity.id.User#userInfo=com.runchain.joying.common.entity.id.UserInfo
            String key = clazz.getName() + "#" + loopFieldName;
            String overrideClassName = "";// PropertyFileUtil.get(key);
            if (StringUtils.isNotBlank(overrideClassName)) {
                Class<?> fieldClazz = Class.forName(overrideClassName);
                ReflectionUtils.setFieldValue(field, "type", fieldClazz);
            }
        }
    }

}